package cn.yz.vo;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页响应VO基类
 */
@Data
public class PageVo<T> {
    
    /**
     * 数据列表
     */
    private List<T> records;
    
    /**
     * 总记录数
     */
    private Long total;
    
    /**
     * 当前页码
     */
    private Long current;
    
    /**
     * 每页大小
     */
    private Long size;
    
    /**
     * 总页数
     */
    private Long pages;
    
    /**
     * 是否有下一页
     */
    private Boolean hasNext;
    
    /**
     * 是否有上一页
     */
    private Boolean hasPrevious;
    
    public PageVo() {}
    
    public PageVo(List<T> records, Long total, Long current, Long size) {
        this.records = records;
        this.total = total;
        this.current = current;
        this.size = size;
        this.pages = (total + size - 1) / size;
        this.hasNext = current < pages;
        this.hasPrevious = current > 1;
    }

    /**
     * 从 MyBatis-Plus 的分页对象转换为 PageVo（带映射）
     */
    public static <T, R> PageVo<R> from(IPage<T> page, Function<T, R> mapper) {
        List<R> mapped = page.getRecords() == null
                ? Collections.emptyList()
                : page.getRecords().stream().map(mapper).collect(Collectors.toList());

        return new PageVo<>(
                mapped,
                page.getTotal(),
                page.getCurrent(),
                page.getSize()
        );
    }

    /**
     * 返回一个空分页对象
     */
    public static <T> PageVo<T> empty() {
        return new PageVo<>(
                Collections.emptyList(),
                0L,
                1L,
                10L
        );
    }
} 